// src/components/EnvSelect/index.tsx
import React, { useEffect, useState } from 'react';
import { ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { get_product_list } from '@/services/order/order_api';
import { Card, Col, Form, Input, Row } from 'antd';
import {  useIntl} from "@umijs/max";

interface ProductSelectProps {
  form?: any;
  formData: any;
  setFormData: (prev: any) => void;
}


const ProductSelect: React.FC<ProductSelectProps> = ({ form, formData, setFormData }) => {
   const intl = useIntl();
  const [options, setOptions] = useState<ServerOption[]>([]);
  const [loading, setLoading] = useState(false);
  const [internalForm] = Form.useForm();
  useEffect(() => {
    if (form) {
      form.internalForms = form.internalForms || [];
      form.internalForms.push(internalForm);
    }
  }, [form]);
  const loadOptions = async () => {
    setLoading(true);
    try {
      const response = await get_product_list();
      if (response.code === 0) {
        setOptions(response.data);
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadOptions();
  }, []);

  return (
  <Card 
    title={intl.formatMessage({ id: 'pages.order.productInfo.title' })} 
    style={{ paddingBottom: '30px', marginBottom: '20px' }} 
    size='small'
  >
    <Form layout="vertical">
      <Row gutter={16}>
        <Col span={24}>
          <Form.Item
            name="referenceNo"
            label={intl.formatMessage({ id: 'pages.order.referenceNo.label' })}
            rules={[{
              validator: (_, value) => {
                if (value && value.length > 30) {
                  return Promise.reject(intl.formatMessage({ id: 'validation.referenceNo.maxLength' }));
                }
                if (/[<>]/.test(value)) {
                  return Promise.reject(intl.formatMessage({ id: 'validation.referenceNo.specialChars' }));
                }
                return Promise.resolve();
              }
            }]}
            initialValue={formData.referenceNo}
          >
            <ProFormText
              placeholder={intl.formatMessage({ id: 'pages.order.referenceNo.placeholder' })}
              fieldProps={{
                onChange: (e) => {
                  setFormData(prev => ({
                    ...prev,
                    referenceNo: e.target.value,
                  }));
                }
              }}
              rules={[{ 
                required: true, 
                message: intl.formatMessage({ id: 'validation.referenceNo.required' }) 
              }]}
            />
          </Form.Item>
        </Col>
      </Row>
    </Form>
  </Card>
);
};

export default ProductSelect;